import React, { useRef, useEffect, useState } from 'react';
import { Tooltip, Spin } from 'antd';
import { InfoCircleOutlined } from '@ant-design/icons';
import { ModalForm, ModalFormProps, ProFormInstance } from '@ant-design/pro-form';
import AssembleForm from '@/components/AssembleForm/AssembleForm';
import { services } from '@/network/api';
import utils from '@/utils/index';
import moment from 'moment';

export type formProps = {
  id?: number;
  _onFinish?: Function;
};

const TableForm: React.FC<ModalFormProps & formProps> = (props) => {
  const { visible, id, _onFinish, ...restProps } = props;
  const formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };
  const formRef = useRef<ProFormInstance<any>>();
  const [spinning, setSpinning] = useState(false);
  const [fields, setFields]: any = useState([]);

  //获取字段信息
  useEffect(() => {
    const getFieldList = async () => {
      const res = await services.getFieldList({
        noPagination: true,
        noMsg: true,
        noThrottle: true,
      });
      //修改表单字段设置
      res?.data.map((item: any) => {
        if (item.name === 'email') {
          item.fieldProps = {
            suffix: (
              <Tooltip title="邮箱创建后作为账号唯一凭证不能更改！">
                <InfoCircleOutlined style={{ color: 'rgba(0,0,0,.45)' }} />
              </Tooltip>
            ),
          };
        }
      });
      setFields(res?.data || []);
    };
    getFieldList();
  }, []);

  //获取用户信息
  useEffect(() => {
    const getUser = async () => {
      setSpinning(true);
      if (id && visible) {
        let res = await services.getUser({ id });
        //角色，部门，岗位，省市,出生日期解析
        res.data.avatar = res.data?.avatar
          ? [
              {
                name: '头像',
                percent: 100,
                status: 'done',
                thumbUrl: res.data?.avatar || '',
                url: res.data?.avatar || '',
              },
            ]
          : [];
        res.data.birthDate = moment(res?.data?.birthDate);
        res.data.access = res?.data?.access?.map((item: any) => {
          return item.id;
        });
        res.data.job = res?.data?.job?.map((item: any) => {
          return item.id;
        });
        res?.data?.province?.id &&
          res?.data?.city?.id &&
          (res.data.area = [res?.data?.province?.id, res?.data?.city?.id]);
        res?.data?.department?.id && (res.data.department = res?.data?.department?.id);
        //自定义字段解析
        res?.data?.custom?.map((item: any) => {
          const [_noUse, _fieldId, fieldType] = item.field.split('_');
          res.data[item.field] = utils.constant.FORM_TYPE_LIST.parseData(item.value, fieldType);
        });

        formRef.current?.setFieldsValue(res?.data);
      } else {
        formRef.current?.resetFields();
      }
      setSpinning(false);
    };
    getUser();
    //设置邮箱禁用
    fields.map((item: any) => {
      if (item.name === 'email') {
        if (id) {
          item.disabled = id;
        } else {
          item.disabled = false;
        }
      }
    });
    setFields(fields);
  }, [id, visible]);

  const onFinish = async (values: any) => {
    values.avatar = values?.avatar?.[0]?.url || '';
    await services.saveUser(values);
    _onFinish?.();
  };
  return (
    <>
      <ModalForm
        omitNil={false}
        preserve={true}
        {...restProps}
        {...formItemLayout}
        formRef={formRef}
        title={id ? '编辑用户' : '新建用户'}
        width="500px"
        visible={visible}
        onFinish={onFinish}
        layout="horizontal"
      >
        <Spin spinning={spinning}>
          {fields.map((item: any) => {
            return <AssembleForm {...item} />;
          })}
        </Spin>
      </ModalForm>
    </>
  );
};

export default TableForm;
